﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Threading;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace WarPigs
{
    public class Screenshot
    {
        private RenderTarget2D screenshotRT;
        private string screenshotPath;
        private Stream stream;

        public Screenshot()
        {
            screenshotPath = System.Windows.Forms.Application.StartupPath + "\\screenshots";
            if (!System.IO.Directory.Exists(screenshotPath))
                System.IO.Directory.CreateDirectory(screenshotPath);
            stream = new FileStream(screenshotPath, FileMode.Create);
        }

        public void TakeScreenshot(GraphicsDevice device)
        {
            int w = device.PresentationParameters.BackBufferWidth;
            int h = device.PresentationParameters.BackBufferHeight;

            screenshotRT = new RenderTarget2D(device, w, h, true, SurfaceFormat.Bgr565, DepthFormat.Depth24);

            device.SetRenderTarget(screenshotRT);

            Thread newThread = new Thread(ScreenshotThread);
            newThread.Start();
        }

        private void ScreenshotThread()
        {
            if (!screenshotRT.IsDisposed)
            {
                string timestampName = DateTime.Now.ToString("yyyyMMdd_HHmmss");

                int i = 1;
                string screenshotPostfix = "";
                while (File.Exists(String.Format("{0}\\{1}{2}.png", screenshotPath, timestampName, screenshotPostfix)))
                {
                    screenshotPostfix = " (" + i + ")";
                    i++;
                }

                string filename = String.Format("{0}\\{1}{2}.png", screenshotPath, timestampName, screenshotPostfix);

                //screenshotRT.Save(filename, ImageFileFormat);
                screenshotRT.SaveAsPng(stream, 800, 600);

                screenshotRT.Dispose();
            }
        }
    }
}